package com.seven.controller;

import com.seven.config.ElasticSearchConfig;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class ElasticSearchController {

    @Autowired
    private ElasticSearchConfig elasticSearchConfig;

    @RequestMapping(value = "/es/createIndex", method = RequestMethod.GET)
    public void createIndexByIndex(){
        String index = "test_1220";
        //校验 索引是否存在
        boolean indexExist= elasticSearchConfig.isIndexExist(index);
        if(!indexExist){
            elasticSearchConfig.createIndex(index);
        }
    }

    @RequestMapping(value = "/es/deleteIndex", method = RequestMethod.GET)
    public void deleteIndexByIndex(){
        String index = "test_1220";
        //校验 索引是否存在
        boolean indexExist= elasticSearchConfig.isIndexExist(index);
        if(indexExist){
            elasticSearchConfig.deleteIndex(index);
        }
    }

    @RequestMapping(value = "/es/saveData", method = RequestMethod.GET)
    public void saveData(){
        String index = "test_1220";
        //校验 索引是否存在
        boolean indexExist= elasticSearchConfig.isIndexExist(index);
        if(indexExist){
            Map<String,String> map = new HashMap<>();
            map.put("key1","Hello ElasticSearch");
            elasticSearchConfig.addData(map,index);
        }
    }

    @RequestMapping(value = "/es/searchData", method = RequestMethod.GET)
    public SearchResponse searchData(){
        String index = "test_1220";
        //校验 索引是否存在
        boolean indexExist= elasticSearchConfig.isIndexExist(index);
        SearchResponse searchResponse = null;
        if(indexExist){
            SearchRequest request = new SearchRequest(index);
            // 指定检索条件
            SearchSourceBuilder builder = new SearchSourceBuilder();
            request.source(builder);
            searchResponse = elasticSearchConfig.searchData(request);
        }
        return searchResponse;
    }

}
